package com.verisette.framework.orm.jpa.vender;

import org.apache.log4j.Logger;

import java.sql.Connection;
import java.sql.SQLException;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceException;

import org.springframework.jdbc.datasource.ConnectionHandle;
import org.springframework.orm.jpa.vendor.HibernateJpaDialect;
import org.springframework.transaction.TransactionDefinition;

import org.springframework.transaction.TransactionException;

/**
 * 
 * For more detail please read http://forum.springsource.org/showthread.php?t=65412
 *
 * @author Pongsatorn Paolanwat(Mix)
 * @since Nov 17, 2010 3:02:16 PM
 * @version 1.0.0
 * @see
 */
public class CustomHibernateJpaDialect extends HibernateJpaDialect {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger
			.getLogger(CustomHibernateJpaDialect.class);

	public Object   beginTransaction(EntityManager entityManager, TransactionDefinition definition)
		throws PersistenceException, SQLException, TransactionException {
		
		//logger.debug("isReadOnly:"+definition.isReadOnly());

		if (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) {
			ConnectionHandle ch = getJdbcConnection(entityManager, definition.isReadOnly());
			Connection conn = ch.getConnection();
			conn.setTransactionIsolation(definition.getIsolationLevel());
		}
		entityManager.getTransaction().begin();
		 
	 	return prepareTransaction(entityManager, definition.isReadOnly(), definition.getName());
	}
	
	@Override
	public ConnectionHandle getJdbcConnection(EntityManager entityManager, boolean readOnly)
	throws PersistenceException, SQLException {
		ConnectionHandle connectionHandle = super.getJdbcConnection(entityManager, readOnly);
		if (null != connectionHandle && null != connectionHandle.getConnection()) {
			if (readOnly) {
				connectionHandle.getConnection().setReadOnly(true) ;
			} else {
				connectionHandle.getConnection().setReadOnly(false);
			}
		}
		return connectionHandle;
	}
	
}
